#ifndef __PG_DBCONNECTION_FARM_H_
#define __PG_DBCONNECTION_FARM_H_

#include <vector>
#include <string>
#include <stdlib.h>
#include <glib.h>
#include <libpq-fe.h>

#include "Debug.h"
#ifdef _THREAD_SAFE
   #include <pthread.h>
#endif

#define HOST_HOST_SPLIT   ","
#define HOST_PORT_SPLIT   ":"

using namespace std;

typedef struct DbParam
{
   string      dbName_;
   string      dbUser_;
   string      dbPass_;
   string      dbPort_;
   unsigned int   dbTimeOut_; 
   unsigned int   dbSkipConnections_;
} DbParam;

typedef struct DbHost
{
   string  dbHost_;
   string  dbPort_;
   long  deadTime_; 
   bool dbLive_;
} DbHost;

typedef struct PDbHost
{
   PGconn *pDb;
   string   dbHost_;
   string   dbPort_;
   long  deadTime_; 
   bool dbLive_;
} PDbHost;

class Farm
{
	public:   
		Farm(DbParam dbParameters) :  myDb_(dbParameters) {
#ifdef   _THREAD_SAFE
			pthread_mutex_init(&_lock, NULL);
			DEBUG1("***************   pthread_mutex_init");
#endif
		}
		virtual PGconn* GetReader() = 0;
		virtual PGconn* GetWriter(int idx) = 0;
		virtual int GetWriterSize() = 0;
		virtual void CloseConnection(PGconn *c, bool write = false) = 0;
		virtual const char * GetError(){  return error_.c_str(); }
		virtual ~Farm() { 
			closeAll();  
#ifdef  _THREAD_SAFE
			DEBUG1("**************    pthread_mutex_destroy");
			pthread_mutex_destroy(&_lock);
#endif
		}
		virtual void Print() = 0;
		//                virtual void SetDebug(bool b) { debug_ = b; } 
	protected:
		virtual void closeAll() { }
		string error_;             
		DbParam myDb_;
		bool debug_;
		int rCount_;

#ifdef  _THREAD_SAFE
                pthread_mutex_t _lock;
#endif

};

#endif
